//-----------------------------------------------------------------------------
// Copyright (c) 2011 David Waby
// Initially created on 31/10/2011
//-----------------------------------------------------------------------------

#include "Global.h"
#include "Map.h"
#include "Tile.h"
		
//-----------------------------------------------------------------------------
Map::Map()
:	m_version(NULL)
,	m_tiles(NULL)
{
} 
	
//-----------------------------------------------------------------------------
Map::~Map()
{
	if (m_tiles)
	{
		int const sizeX = m_size[X];
		int const sizeY = m_size[Y];

		for (int xDimension = 0; xDimension < sizeX; ++xDimension)
		{
			for (int yDimension = 0; yDimension < sizeY; ++yDimension)
			{
				delete m_tiles[xDimension][yDimension];
			}
			delete [] m_tiles[xDimension];
		}
		delete [] m_tiles;
		m_tiles = 0;
	}
}

//-----------------------------------------------------------------------------
void Map::Construct()
{
	int const sizeX = m_size[X];
	int const sizeY = m_size[Y];

	// Create the map array for all the tiles
	m_tiles = new Tile**[sizeX];
	for (int xDimension = 0; xDimension < sizeX; ++xDimension)
	{
		m_tiles[xDimension] = new Tile*[sizeY];
		for (int yDimension = 0; yDimension < sizeY; ++yDimension)
		{
			m_tiles[xDimension][yDimension] = new Tile(xDimension, yDimension);
		}
	}
}

//-----------------------------------------------------------------------------
void Map::EnterTile(Point2 const * i_point2)
{
	Tile * tile = GetTile(i_point2);
	tile->EnterTile();
}

//-----------------------------------------------------------------------------
void Map::UseTile(Point2 const * i_point2)
{
	Tile * tile = GetTile(i_point2);
	tile->UseTile();
}

//-----------------------------------------------------------------------------
void Map::ExitTile(Point2 const * i_point2)
{
	Tile * tile = GetTile(i_point2);
	tile->ExitTile();
}

//-----------------------------------------------------------------------------
void Map::Serialise(Json::Value * o_root) const
{
}

//-----------------------------------------------------------------------------
void Map::Deserialise(Json::Value const * i_root)
{
	m_version = (*i_root)["version"].asInt();

	m_size.Deserialise(&(*i_root)["size"]);
	m_startPosition.Deserialise(&(*i_root)["start"]);

	// Construct the map
	Construct();

	Json::Value tiles = (*i_root)["tiles"];
	if (tiles.isArray())
	{
		// Loop through all of the tiles and handle reading data
		Point2 position;
		Tile * tile = NULL;
		for (Json::ArrayIndex counter = 0; counter < tiles.size(); ++counter)
		{
			Json::Value element = tiles[counter]["loc"];
			position.Deserialise(&element);

			tile = GetTile(&position);
			tile->Deserialise(&tiles[counter]);
		}
	}
}